package com.example.wan_android.ui.activity

import android.util.Log
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.wan_android.BR
import com.example.wan_android.R
import com.example.wan_android.adapter.HotWordAdapter
import com.example.wan_android.adapter.SearchHistoryAdapter
import com.example.wan_android.databinding.ActivitySearchBinding
import com.example.wan_android.tools.SpacesItemDecoration
import com.example.wan_android.viewmodel.SearchViewModel
import kotlinx.coroutines.launch

class SearchActivity : BaseActivity<ActivitySearchBinding, SearchViewModel>(
    SearchViewModel::class.java,
    R.layout.activity_search,
    BR.viewModel
) {
    private val adapter by lazy {
        HotWordAdapter(mViewModel!!)
    }
    private val searchHistoryAdapter by lazy {
        SearchHistoryAdapter(mViewModel!!)
    }

    override fun initView() {
        mViewModel?.context = this@SearchActivity
        mViewDataBinding?.rvHotWord?.addItemDecoration(SpacesItemDecoration(20))
        mViewDataBinding?.rvHotWord?.adapter = adapter
        mViewDataBinding?.rvHotWord?.layoutManager = GridLayoutManager(this, 3)
        mViewDataBinding?.rvSearchHistory?.addItemDecoration(SpacesItemDecoration(10))
        mViewDataBinding?.rvSearchHistory?.adapter = searchHistoryAdapter
        mViewDataBinding?.rvSearchHistory?.layoutManager = LinearLayoutManager(this)

        mViewModel?.hotWordListData?.observe(this) {
            it.onSuccess {
                adapter.setListData(it)
            }
        }

        mViewModel?.allSearchHistory?.observe(this) {
            searchHistoryAdapter.setListData(it)
        }
        mViewDataBinding?.tvSearchBtn?.setOnClickListener(
            {
                lifecycleScope.launch {
//                    mViewModel?.addSearchHistory(mViewDataBinding?.etSearchContent?.text.toString())
                    mViewModel?.jumpSearchResult(
                        mViewDataBinding?.etSearchContent?.text.toString(),
                        mViewDataBinding?.etSearchContent?.text.toString()
                    )
                }
            }
        )
    }

}